import threading
import socket
import time


class mainThread(threading.Thread):
    def __init__(self, conf):
        threading.Thread.__init__(self)
        self.conf = conf
        self.host = "192.168.31.211"
        self.port = 8020
        self.web = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.guid = ""
        self.isRun = True

    def stop(self):
        self.isRun = False
        self.web.close()

    def do_Send(self, text):
        # text["guid"] = self.guid
        # if self.isRun:
        self.web.send(f"{text}".encode("utf-8"))

    def do_QueueSend(self):
        """发送队列消息"""
        while self.isRun:
            time.sleep(0.1)
            if not self.conf["send"].empty():
                msg = self.conf["send"].get()
                self.do_Send(msg)

    def run(self):
        print("开始网络线程...")
        buff = 512
        self.web.connect((self.host, self.port))
        # 查看默认发送接收缓冲区大小
        # recv_buff = self.web.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        # send_buff = self.web.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        # print(f"默认接收缓冲区大小：{recv_buff}。默认发送缓冲区大小：{send_buff}")
        threading.Thread(target=self.do_QueueSend).start()
        while self.isRun:
            time.sleep(0.1)
            try:
                s = self.web.recv(buff)
                if not s:
                    print("~~~~~~失败~~~~~")
                    break
                self.msgManager(s.decode("utf-8"))
            except BaseException as err:
                print("ERR:", err)
                break

        print("结束网络线程...")

    def msgManager(self, msg):
        """消息接收管理器"""
        # print(len(msg))
        try:
            data = eval(msg)
        except BaseException as err:
            print(f"解码消息失败, 游戏终止. {err}")
            self.stop()
        # print("Recv:", type(data), data)
        # print("Recv:", data)
        # --------------------- 初始化消息 ------------------------- #
        # if data.get("act") == "init":
        #     self.guid = data.get("guid")
        #     self.conf["send"].put({"act": "enter", "guid": self.guid, "data": "room_1"})
        #     return
        # --------------------- 队列消息 --------------------------- #
        self.conf["recv"].put(data)

    #     # --------------------- 公共消息 --------------------------- #
    #     guid = data.get("guid")
    #     if not guid == self.guid:
    #         self.newsManager(data)
    #         return
    #     # -------------------- 私有消息 ---------------------------- #
    #     if data.get("act") == "wait":
    #         self.conf[0] = "wait"
    #         self.conf[1] = ["战前准备，等待就绪.", "1 准备就绪"]
    #     elif data.get("act") == "ready":
    #         self.conf[0] = "ready"
    #         self.conf[1] = ["准备就绪,等待进入战场.", "1 取消准备"]

    # def newsManager(self, data):
    #     """公共消息管理器"""
    #     # print("公共消息:", data)
    #     if data.get("act") == "lock":
    #         self.conf[0] = "lock"
    #         self.conf[1] = [f'开始倒计时: {data.get("data")}']
    #     elif data.get("act") == "fight":
    #         self.conf[0] = "fight"
    #         self.conf[1] = None
    #     elif data.get("act") == "gens":
    #         self.conf[3].put(data)
    #     else:
    #         pass
